package com.zja.www.service.impl;

import com.zja.www.dao.DepartmentDao;
import com.zja.www.entity.Department;
import com.zja.www.service.DepartmentService;

import java.util.Collections;
import java.util.List;

public class DepartmentServiceImpl implements DepartmentService {
    private final DepartmentDao departmentDao;

    public DepartmentServiceImpl(DepartmentDao departmentDao) {
        this.departmentDao = departmentDao;
    }

    @Override
    public boolean addDepartment(Department department) {
        if (department == null || department.getName() == null || department.getName().trim().isEmpty()) {
            return false;
        }
        return departmentDao.insert(department);
    }

    @Override
    public boolean deleteDepartment(int id) {
        if (id <= 0) {
            return false;
        }
        return departmentDao.deleteById(id);
    }

    @Override
    public boolean updateDepartment(Department department) {

        if (department == null || department.getId() <= 0) {
            return false;
        }

        // 校验科室是否存在
        if (departmentDao.selectById(department.getId()) == null) {
            return false;
        }

        return departmentDao.update(department);
    }

    @Override
    public Department getDepartmentById(int id) {
        if (id <= 0) {
            return null;
        }
        return departmentDao.selectById(id);
    }

    @Override
    public List<Department> getAllDepartments() {
        List<Department> departments = departmentDao.selectAll();
        return departments != null ? departments : Collections.emptyList();
    }

    @Override
    public List<Department> searchDepartmentsByName(String name) {
        if (name == null || name.trim().isEmpty()) {
            return Collections.emptyList();
        }
        List<Department> departments = departmentDao.selectByName(name.trim());
        return departments != null ? departments : Collections.emptyList();
    }
}
